const app = getApp()
import util from '../../../utils/util'
import {
  ServiceDetail,
  GetTemplateConfig,
  ApplyVolunt
} from '../../../config/api'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    uid: '',
    detail: '',
    tmplIds: [], // 模板消息id集合
  },

  onLoad: function(options) {
    console.log(options)
    let id = options.id;
    console.log('id', id)

    let member = wx.getStorageSync('member')
    let grider_storge = wx.getStorageSync('grider')

    if (member) {
      this.setData({
        member
      })
    } else if (grider_storge && !member) {
      wx.showModal({
        showCancel: false,
        content: '您不是村民，暂不能操作此功能',
        success(res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '/pages/index/index',
            })
          }
        }
      })
      return;
    } else {
      wx.redirectTo({
        url: '/pages/register/register',
      })
      return;
    }

    if (wx.getStorageSync('member')) {
      let uid = wx.getStorageSync('member').id;
      this.setData({
        uid: uid
      })
    }

    this.setData({
      id: id
    })
    this.getDetail()

    this.getTmplIds(); // 调用模板id集合
  },

  getDetail() {
    let that = this;
    util.apiRequest(ServiceDetail, {
      id: that.data.id
    }, null).then(r => {
      console.log('服务详情', r)
      that.setData({
        detail: r.data.data
      })
    })
  },

  getTmplIds() { // 获取模板消息id集合
    let that = this;
    util.apiRequest(GetTemplateConfig, {
      vollege_id: app.globalData.vollege_id
    }, null).then(r => {
      console.log('模板id：', r)
      let tmplIds = r.data.data.map(item => {
        return item.value.template_id
      })
      console.log('66tmplIds:', tmplIds)
      that.setData({
        tmplIds
      })
    })
  },

  onApplyVolunt() {
    let that = this;
    let params = {
      id: this.data.id,
      provider: this.data.uid
    }
    console.log('参数', params)
    wx.requestSubscribeMessage({
      tmplIds: that.data.tmplIds,
      success(res) {
        console.log('成功', res)
      }
    }) 

    wx.showModal({
      title: '提示',
      content: '确认申请提供服务?',
      success(res) {
        if (res.confirm) {
          util.apiRequest(ApplyVolunt, params, null).then(r => {
            console.log('申请服务：', r)
            if (r.data.code == 1) {
              wx.showModal({
                showCancel: false,
                content: r.data.info,
                success(res) {
                  if (res.confirm) {
                    wx.redirectTo({
                      url: "/pages/culture/cultureList/cultureList"
                    })
                  }
                }
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})